
#include "member_BDateEdit.h"
#include "member_BObject.h"

using namespace BWE;

member_BDateEdit::member_BDateEdit(BDateEdit* dateEdit)
{
	boss = dateEdit;
	readOnly = false;
	synchro = false;
	align = Align_Center;
	format.reset("yyyy-mm-dd");
	blinkTick = 0;
	blinkTime = 1;
	blinkShown = false;

	dirty = true;
	dirtyText = true;
	editing = false;
	hoverIndex = -1;
	pressed = false;
	pressedIndex = -1;
}
member_BDateEdit::~member_BDateEdit()
{

}

void member_BDateEdit::freshRects()
{
	const BStyle* style = boss->realStyle();
	const BFont* font = boss->realFont();
	if (!font)
		return;

	textArea = boss->centerRect();

	if (block.dirty)
	{
		block.adjust(0);
	}
	BRect textRect = textArea.align(align, block.textSize);
	block.rect = textRect;
}
BLine2 member_BDateEdit::inputLine()
{
	BLine2 line;
	if (block.cells.check(block.index))
	{
		BRect cellRect = block.cells[block.index].rect + block.rect.pos();
		line.setBegin(cellRect.left(), block.rect.top());
		line.setEnd(cellRect.left(), block.rect.bottom());

	}
	else
	{
		BRect cellRect = block.cells.last().rect + block.rect.pos();
		line.setBegin(cellRect.right(), block.rect.top());
		line.setEnd(cellRect.right(), block.rect.bottom());
	}
	if (!textArea.contain(line.begin()))
	{
		BPoint point = textArea.wrap(line.begin());
		BPoint offset = point - line.begin();
		block.rect.move(offset.x(), 0);
		line.move(offset.x(), 0);
	}
	return line;
}
void member_BDateEdit::textEdited()
{
	dirty = true;
	editing = true;

	int year = 0;
	int month = 0;
	int day = 0;

	int ybegin = format.find('y');
	int yend = format.rfind('y') + 1;
	int mbegin = format.find('m');
	int mend = format.rfind('m') + 1;
	int dbegin = format.find('d');

	BString text = block.text;
	text.remove(0, ybegin);
	BString split;
	if (format.substr(split, yend, mbegin))
	{
		year = text.toInt();
		int end = text.find(split);
		text.remove(0, end + split.size());
	}
	if (format.substr(split, mend, dbegin))
	{
		month = text.toInt();
		int end = text.find(split);
		text.remove(0, end + split.size());
	}
	if (text.isNumber())
	{
		day = text.toInt();
	}

	date.set(year, month, day);
	object_member(boss)->emit(Signal_DateEdited, date);
	boss->fresh();
}

bool member_BDateEdit::removeCode()
{
	if (block.cells.check(block.index))
	{
		ICodeCell& cell = block.cells[block.index];
		if (cell.code >= '0' && cell.code <= '9')
		{
			block.cells.remove(block.index);
			block.flush();
			return true;
		}
	}
	return false;
}
bool member_BDateEdit::removeSelection()
{
	int begin = bMin(block.index, block.index + block.count);
	if (block.cells.check(begin) && block.count)
	{
		int pos = begin;
		for (int i = 0; i < block.count; i++)
		{
			ICodeCell& cell = block.cells[pos];
			if (cell.code >= '0' && cell.code <= '9')
				block.cells.remove(pos);
			else
				pos++;
		}
		block.index = begin;
		block.count = 0;
		block.flush();
		return true;
	}
	return false;
}
